package com.sgb.kjwl.view.ui.activity.self;

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.hardware.Camera;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.RelativeLayout;

import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;

import com.luck.picture.lib.tools.ScreenUtils;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityCameraBinding;
import com.sgb.kjwl.utils.FileUtils;
import com.sgb.kjwl.utils.ImageUtil;
import com.sgb.kjwl.utils.camera.CameraUtils;
import com.sgb.kjwl.view.constant.RouterKey;
import com.sgb.kjwl.view.ui.activity.transport.PayGoodsOrderActivity;
import com.swgk.core.base.permission.MPermission;
import com.swgk.core.base.permission.annotation.OnMPermissionDenied;
import com.swgk.core.base.permission.annotation.OnMPermissionGranted;
import com.swgk.core.base.permission.annotation.OnMPermissionNeverAskAgain;
import com.swgk.core.util.MToast;
import com.swgk.core.util.PermissionUtils;

import java.io.File;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * @author: 王彬臣
 * @date: 2021/4/7
 * @Description: 自定义拍照界面
 */
public class CameraActivity extends AppActivity {
    ActivityCameraBinding binding;
    private static final int BASIC_PERMISSION_REQUEST_CODE = 120;
    private static final String[] BASIC_CAMERA_PERMISSIONS = new String[]{
            android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
            android.Manifest.permission.READ_EXTERNAL_STORAGE,
            android.Manifest.permission.CAMERA
    };
    int type;
    private Bitmap mCropBitmap;

    public static void start(Activity context, int type, String title,int code) {
        Intent intent = new Intent(context, CameraActivity.class);
        intent.putExtra(RouterKey.TYPE, type);
        intent.putExtra(RouterKey.NAME, title);
        context.startActivityForResult(intent,code);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        requestCameraPermission();

    }

    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(this, R.layout.activity_camera);
        binding.setOnClick(this);
        type = getIntent().getIntExtra(RouterKey.TYPE, 0);
        if (type == 0) {
            binding.ivHeader.setVisibility(View.VISIBLE);
        }
        String title = getIntent().getStringExtra(RouterKey.NAME);
        binding.backTitle.setText(title);
        float screenHeight = ScreenUtils.getScreenHeight(this);
        float height = (int) (screenHeight * 0.72f);
        float width = (int) (height * 45.0f/ 27.0f);
        RelativeLayout.LayoutParams cropParams = new RelativeLayout.LayoutParams((int) width, (int) height);
        cropParams.addRule(RelativeLayout.CENTER_IN_PARENT);
        binding.rlCropImage.setLayoutParams(cropParams);

        binding.imgCrop.setLayoutParams(cropParams);
        checkPerPermissions();
    }

    private void checkPerPermissions() {

        if(PermissionUtils.checkPermissionsGroup(this, BASIC_CAMERA_PERMISSIONS)) {
            /*增加0.5秒过渡界面，解决个别手机首次申请权限导致预览界面启动慢的问题*/
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            binding.cameraPreview.setVisibility(View.VISIBLE);
                        }
                    });
                }
            }, 500);
        }
    }

    protected void requestCameraPermission() {
        MPermission.printMPermissionResult(true, this, BASIC_CAMERA_PERMISSIONS);
        MPermission.with(this)
                .setRequestCode(BASIC_PERMISSION_REQUEST_CODE)
                .permissions(BASIC_CAMERA_PERMISSIONS)
                .request();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        MPermission.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    @OnMPermissionGranted(BASIC_PERMISSION_REQUEST_CODE)
    public void onBasicPermissionSuccess() {
        MPermission.printMPermissionResult(false, this, BASIC_CAMERA_PERMISSIONS);
        checkPerPermissions();
    }

    @OnMPermissionDenied(BASIC_PERMISSION_REQUEST_CODE)
    @OnMPermissionNeverAskAgain(BASIC_PERMISSION_REQUEST_CODE)
    public void onBasicPermissionFailed() {
        MToast.showToast(this, "授权失败无法使用相机");
        MPermission.printMPermissionResult(false, this, BASIC_CAMERA_PERMISSIONS);
        finish();
    }

    @Override
    public void onMultiClick(View v) {
        switch (v.getId()) {
            case R.id.back_title:
                finish();
                break;
            case R.id.iv_take_photo:
                takePhoto();
                break;
        }
    }
    /**
     * 拍照
     */
    private void takePhoto() {
        binding.cameraPreview.setEnabled(false);
        CameraUtils.getCamera().setOneShotPreviewCallback(new Camera.PreviewCallback() {
            @Override
            public void onPreviewFrame(final byte[] bytes, Camera camera) {
                final Camera.Size size = camera.getParameters().getPreviewSize(); //获取预览大小
                camera.stopPreview();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        final int w = size.width;
                        final int h = size.height;
                        Bitmap bitmap = ImageUtil.getBitmapFromByte(bytes, w, h);
                        cropImage(bitmap);
                    }
                }).start();
            }
        });
    }

    /**
     * 裁剪图片
     */
    @SuppressLint("AutoDispose")
    private void cropImage(Bitmap bitmap) {
        /*计算扫描框的坐标点*/
        float left =  binding.rlCropImage.getLeft();
        float top = binding.rlCropImage.getTop();
        float right = binding.rlCropImage.getRight();
        float bottom = binding.rlCropImage.getBottom();

        /*计算扫描框坐标点占原图坐标点的比例*/
        float leftProportion = left / binding.cameraPreview.getWidth();
        float topProportion = top / binding.cameraPreview.getHeight();
        float rightProportion = right / binding.cameraPreview.getWidth();
        float bottomProportion = bottom / binding.cameraPreview.getBottom();

        /*自动裁剪*/
        mCropBitmap = Bitmap.createBitmap(bitmap,
                (int) (leftProportion * (float) bitmap.getWidth()),
                (int) (topProportion * (float) bitmap.getHeight()),
                (int) ((rightProportion - leftProportion) * (float) bitmap.getWidth()),
                (int) ((bottomProportion - topProportion+0.01) * (float) bitmap.getHeight()));
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                setCropLayout();
                binding.imgCrop.setImageBitmap(mCropBitmap);
            }
        });
        Observable.timer(500, TimeUnit.MILLISECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(aLong -> {

                    String imagePath = new StringBuffer().append(FileUtils.getImageCacheDir(CameraActivity.this)).append(File.separator)
                            .append(System.currentTimeMillis()).append(".jpg").toString();

                    if (ImageUtil.save(mCropBitmap, imagePath, Bitmap.CompressFormat.JPEG)) {
                        ImageUtil.getImage(imagePath);
                        Intent intent = new Intent();
                        intent.putExtra("imagePath", imagePath);
                        setResult(RESULT_OK, intent);
                        finish();
                    }
                });

    }

    /**
     * 设置裁剪布局
     */
    private void setCropLayout() {

        binding.cameraPreview.setVisibility(View.GONE);
        binding.rlCropImage.setVisibility(View.GONE);
        binding.ivHeader.setVisibility(View.GONE);
    }
    @Override
    protected void onStart() {
        super.onStart();
        binding.cameraPreview.onStart();
    }

    @Override
    protected void onStop() {
        super.onStop();
        binding.cameraPreview.onStop();
    }
}
